package com.jqsoft.launcher.activity.childCareManagement;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Color;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.nfc.NfcAdapter;
import android.nfc.tech.NfcB;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.garea.device.plugin.DevicePluginCategory;
import com.garea.device.plugin.DevicePluginManager;
import com.garea.device.plugin.IDevicePlugin;
import com.garea.device.plugin.idcard.IDCardInspector;
import com.garea.device.plugin.idcard.IIDCardDevice;
import com.garea.device.plugin.idcard.IIDCardPersonInfo;
import com.garea.device.plugin.idcard.OnIDCardListener;
import com.jqsoft.launcher.activity.JQActivity;
import com.jqsoft.launcher.activity.bean.LittleChildBean;
import com.jqsoft.launcher.activity.bean.UserLoginInfo;
import com.jqsoft.launcher.activity.gairui.XDpersonActivity;
import com.jqsoft.launcher.activity.setting.SubmitInfoListActivity;
import com.jqsoft.launcher.common.BphsConstants;
import com.jqsoft.launcher.common.BphsURL;
import com.jqsoft.launcher.common.Constant;
import com.jqsoft.launcher.R;
import com.jqsoft.launcher.patientdb.PatientDao;
import com.jqsoft.launcher.tool.AbstractViewHolder;
import com.jqsoft.launcher.util.CommonUtil;
import com.jqsoft.launcher.util.GotoActivityHelper;
import com.jqsoft.launcher.util.Log;
import com.jqsoft.launcher.util.MessageTools;
import com.jqsoft.launcher.util.StringTools;
import com.jqsoft.launcher.util.WebServiceUtils;
import com.otg.idcard.OTGReadCardAPI;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

//import cn.jqsoft.bphs.mpah.activity.gairui.CardActivity;


/**
 * 儿童保健管理
 *
 * @author gujunqi date：2014-2-27
 */
public class ChildCareManageActivity extends JQActivity implements
		OnClickListener, OnScrollListener {
	private final String tag = "ChildCareManageActivity";
	private ListView listview;// 列表
	private ListAdapter adapter;
	private TextView Readingtext;

	private CheckBox xzCheckbox, current_xzCheckbox;
	private Button chaxuan_btn, quick_suifang, totalcount_bt, weitj_suifang,
			xindian_jiance_bt, card_chaxuan_btn;
	private EditText name_et, dangan_num_et, shengfenzheng_et;
	private String content;
	private List<LittleChildBean> infoList = new ArrayList<LittleChildBean>();
	private boolean notfirstTime = false, isThreadrun = false;
	private long allcount = 0;

	private View moreView;
	private LinearLayout progressBar_ll; // 更多等待层
	private Button moreButton;
	private int jiciNum = 1;// 第几次点击加载更多

	private LittleChildBean xuanzhong_tiao;
	private String name_str, dangan_num_str, shengfenzheng_str;
	/* 请求码 */
	private static final int IMAGE_REQUEST_CODE = 0;
	private static final int CAMERA_REQUEST_CODE = 1;
	private static final int RESULT_REQUEST_CODE = 2;

	private static final int IMAGE_REQUEST_CODE2 = 3;
	private static final int CAMERA_REQUEST_CODE2 = 4;
	private static final int RESULT_REQUEST_CODE2 = 5;

	private static final int IMAGE_REQUEST_CODE3 = 6;
	private static final int CAMERA_REQUEST_CODE3 = 7;
	private static final int RESULT_REQUEST_CODE3 = 8;
	private static String DB_NAME;
	private static final int DB_VERSION = 2;
	private static DatabaseHelper mOpenHelper;
	private static SQLiteDatabase db2;

	private static final int SETTING_SERVER_IP = 11;
	private static final int SETTING_BT = 22;
	public static String remoteIPA = "";
	public static String remoteIPB = "";
	public static String remoteIPC = "";
	private int mode = 2;// 1,OTG; 2, NFC; //3, Bluetooth;

	private NfcAdapter mAdapter = null;
	// private ReadCardAPI NFCReadCardAPI;
	private OTGReadCardAPI ReadCardAPI;
	private PendingIntent pi = null;
	// �˵�����޷���Ӧ�ʹ����Intent
	private IntentFilter tagDetected = null;
	private String[][] mTechLists;
	private Intent inintent = null;

	private int readflag = 0;
	private BluetoothAdapter btAdapt;
	private static final int REQUEST_ENABLE_BT = 2;
	public static String EXTRA_DEVICE_ADDRESS = "device_address";
	public static String addressmac = "";

	public static final int MESSAGE_VALID_OTGBUTTON = 15;
	public static final int MESSAGE_VALID_NFCBUTTON = 16;
	public static final int MESSAGE_VALID_BTBUTTON = 17;
	public static final int MESSAGE_VALID_PROCESS = 1001;

	public static String DB_CREATE_TABLE_IPCONFIG = "CREATE TABLE IF NOT EXISTS [setipconfig] "
			+ "([ID] INTEGER PRIMARY KEY,[IP] VARCHAR)";

	private static class DatabaseHelper extends SQLiteOpenHelper {
		DatabaseHelper(Context context) {
			super(context, DB_NAME, null, DB_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db2) {
			Log.e("ERROR", "test here DBOperation this channel onCreate");
			db2.execSQL(DB_CREATE_TABLE_IPCONFIG);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		}
	}

	@Override
	protected int getContentLayout() {
		return R.layout.childcare_management;
	}
	private IDCardInspector mInspector;
	private IIDCardDevice mDevice;
	@Override
	protected void initGui() {
		IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
		this.registerReceiver(mUsbReceiver, filter);
		Readingtext = (TextView) findViewById(R.id.Readingtext);
		listview = (ListView) findViewById(R.id.hbp_diagnosis_lv);
		chaxuan_btn = (Button) findViewById(R.id.chaxuan_btn);
		chaxuan_btn.setOnClickListener(ChildCareManageActivity.this);
		card_chaxuan_btn = (Button) findViewById(R.id.card_chaxuan_btn);
		UserLoginInfo userinfo = UserLoginInfo.getInstances();
		if (userinfo.getsAndroidReader().equals("0")) {
			card_chaxuan_btn.setVisibility(View.GONE);
		}
		card_chaxuan_btn.setOnClickListener(this);
		quick_suifang = (Button) findViewById(R.id.quick_suifang);
		quick_suifang.setOnClickListener(ChildCareManageActivity.this);
		totalcount_bt = (Button) findViewById(R.id.totalcount_bt);
		dangan_num_et = (EditText) findViewById(R.id.dangan_num_et);
		name_et = (EditText) findViewById(R.id.name_et);
		shengfenzheng_et = (EditText) findViewById(R.id.shengfenzheng_et);
		weitj_suifang = (Button) findViewById(R.id.weitj_suifang);
		weitj_suifang.setOnClickListener(ChildCareManageActivity.this);
		xindian_jiance_bt = (Button) findViewById(R.id.xindian_jiance_bt);
		xindian_jiance_bt.setOnClickListener(ChildCareManageActivity.this);
		mInspector = DevicePluginManager.getDeviceInspector(DevicePluginCategory.DEV_PLUGIN_CATEGORY_IDCARD_2,
				this);

		mInspector.setOnIDCardDevicePluginListener(new IDCardInspector.OnIDCardDevicePluginListener() {

			@Override
			public void onDiscoverDevice(IIDCardDevice dev) {
				Toast.makeText(ChildCareManageActivity.this,
						"已连接", Toast.LENGTH_SHORT).show();
				mDevice = dev;
				//自动连接
				dev.setOnDevicePluginStateListener(new DevStateListener());
				dev.setOnIDCardListener(mCardListener);
				dev.init();
			}

			@Override
			public void onMonitorDevice(IIDCardDevice dev) {
				//USB不用本函数
			}
			@Override
			public void onRemovedDevice(IIDCardDevice dev) {
				if (mDevice != null) {
					mDevice.close();
					mDevice.uninit();
					mDevice = null;
				}
			}
		});

		mInspector.init();
		mInspector.searchDevice();
	}
	private class DevStateListener implements IDevicePlugin.OnDevicePluginStateListener {


		public DevStateListener() {

		}

		@Override
		public void onDeviceOpened() {

		}

		@Override
		public void onDeviceInited() {
			mDevice.open();
		}

		@Override
		public void onDeviceUninited() {
			//
		}

		@Override
		public void onDeviceClosed() {
			//
		}

		@Override
		public void onStateChanged(int arg0, int arg1) {
			//
		}
	}
	private OnIDCardListener mCardListener = new OnIDCardListener() {

		@Override
		public void onReceived(IIDCardPersonInfo d) {
			shengfenzheng_et.setText(d.getID().trim());
            name_et.setText(d.getName().trim());
			xuanzhong_tiao = null;
			current_xzCheckbox = null;
			jiciNum = 1;
			moreButton.setVisibility(View.VISIBLE);
			name_str = name_et.getText().toString().trim();
			dangan_num_str = dangan_num_et.getText().toString().trim();
			shengfenzheng_str = shengfenzheng_et.getText().toString().trim();
			if (infoList.size() > 0) {
				listview.removeFooterView(moreView);
			}
			infoList.clear();
			allcount = 0;
			notfirstTime = false;
			loadWaitPanel();
			new Thread(sendable).start();

		}

		@Override
		public void onReadFailed() {
        Toast.makeText(ChildCareManageActivity.this,"读卡失败",Toast.LENGTH_SHORT).show();
		}
	};
	@Override
	protected void initAction() {
		setGoBack();
		listview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				LittleChildBean obj = (LittleChildBean) listview
						.getItemAtPosition(position);

				xuanzhong_tiao = obj;
				xzCheckbox = (CheckBox) view.findViewById(R.id.xuanzhong_cb);
				for (int i = 0; i < infoList.size(); i++) {
					infoList.get(i).setCheck(false);
				}
				obj.setCheck(true);
				if (current_xzCheckbox != null) {
					current_xzCheckbox.setChecked(false);
				}
				xzCheckbox.setChecked(true);
				current_xzCheckbox = xzCheckbox;
				adapter.notifyDataSetChanged();
			}

		});
		listview.setOnScrollListener(this);
	}

	@Override
	protected void initData() {
		setTitle("儿童保健管理");
		// if(BphsConstants.sAndroidReader){
		// chaxuan_btn.setText("读身份证查询");
		// dangan_num_et.setEnabled(false);
		// name_et.setEnabled(false);
		// shengfenzheng_et.setEnabled(false);
		// dangan_num_et.setBackgroundDrawable(getResources().getDrawable(drawable.shape_grayall_corner));
		// name_et.setBackgroundDrawable(getResources().getDrawable(drawable.shape_grayall_corner));
		// shengfenzheng_et.setBackgroundDrawable(getResources().getDrawable(drawable.shape_grayall_corner));
		// }
		moreView = getLayoutInflater().inflate(
				R.layout.finance_fund_pagination_more, null);
		moreButton = (Button) moreView.findViewById(R.id.loadMore);
		moreButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (notfirstTime && (allcount > infoList.size())
						&& !isThreadrun) {
					moreButton.setVisibility(View.GONE);
					progressBar_ll.setVisibility(View.VISIBLE);
					jiciNum++;
					new Thread(sendable).start();
				}
			}
		});
		progressBar_ll = (LinearLayout) moreView
				.findViewById(R.id.progressBar_ll);

		Readingtext.setVisibility(View.GONE);
		Readingtext.setText("      正在读卡，请稍候...");
		Readingtext.setTextColor(Color.RED);
		DB_NAME = "/sdcard/yishu/usingservice.db";
		mOpenHelper = new DatabaseHelper(this);
		db2 = mOpenHelper.getWritableDatabase();
		String sql = "";
		Cursor cur;
		sql = "select IP from setipconfig where ID=4;";
		cur = db2.rawQuery(sql, null);
		if (cur.moveToFirst() == true) {
			while (!cur.isAfterLast()) {
				addressmac = cur.getString(0).trim();
				break;
			}
		}
		cur.close();
		db2.close();
		mOpenHelper.close();
		btAdapt = BluetoothAdapter.getDefaultAdapter();// ��ʼ��������������

		ReadCardAPI = new OTGReadCardAPI(getApplicationContext());
		// ReadCardAPI.setpathflag(2);
		// ReadCardAPI.setlogflag(1);
		// mAdapter = NfcAdapter.getDefaultAdapter(this);
		mAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext());
		if (mAdapter == null) {
			// ReadCardAPI.writeFile("pass new test 2.1");
		} else {
			init_NFC();
			// ReadCardAPI.writeFile("pass new test 2.2");
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		dismissrogressBar();
		if (requestCode == SETTING_BT) {
			if (resultCode != Activity.RESULT_OK) {
				return;
			}
			String address = data.getStringExtra(EXTRA_DEVICE_ADDRESS);
			mOpenHelper = new DatabaseHelper(this);
			db2 = mOpenHelper.getWritableDatabase();
			String sql = "select IP from setipconfig where ID=4;";
			int p = 0;
			Cursor cur;
			cur = db2.rawQuery(sql, null);
			if (cur.moveToFirst() == true) {
				while (!cur.isAfterLast()) {
					p++;
					break;
				}
			}
			cur.close();

			if (p == 0) {
				sql = "insert into setipconfig (ID,IP) values(4,'" + address
						+ "');";
				db2.execSQL(sql);
			} else {
				sql = "update setipconfig set IP='" + address + "'"
						+ " where ID=4" + ";";
				db2.execSQL(sql);
			}
			db2.close();
			mOpenHelper.close();
			addressmac = address;
			ReadCardAPI.setmac(address);

		}
		if (data != null) {
			String cardName = data.getStringExtra("cardName");
			String cardNumber = data.getStringExtra("cardNumber");
			if (requestCode == 1) {
				if (StringUtils.isNotBlank(cardName)
						&& StringUtils.isNotBlank(cardNumber)) {
					name_et.setText(cardName);
					shengfenzheng_et.setText(cardNumber);
					name_str = cardName;
					shengfenzheng_str = cardNumber;
					if (infoList.size() > 0) {
						listview.removeFooterView(moreView);
					}
					infoList.clear();
					allcount = 0;
					notfirstTime = false;
					loadWaitPanel();
					new Thread(sendable).start();
				} else {
					Toast.makeText(this, "读身份证信息失败", Toast.LENGTH_SHORT).show();
				}
			}
		} else {
			Toast.makeText(this, "读身份证信息失败", Toast.LENGTH_SHORT).show();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private Handler myhandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constant.MSG_LOAD_OVER:
				adapter = new ListAdapter();
				notfirstTime = true;
				if (!(infoList.size() == allcount || allcount == 0 || infoList
						.size() <= 0)) {
					// listview.removeFooterView(moreView);
					listview.addFooterView(moreView);
				}
				listview.setAdapter(adapter);
				String count;
				if (infoList.size() > allcount) {
					count = "共计" + infoList.size() + "条）";
				} else {
					count = "共计" + allcount + "条）";
				}
				totalcount_bt.setText("（已加载" + infoList.size() + "条/" + count);
				if (infoList.size() == 0) {
					MessageTools.showDialogOk(ctx, "无此人信息");
				}
				dismissrogressBar();
				progressBar_ll.setVisibility(View.GONE);
				break;
			case Constant.SHOW_UPDATE:
				if (allcount == 0)
					allcount = infoList.size();
				totalcount_bt.setText("（已加载" + infoList.size() + "条/" + "共计"
						+ allcount + "条）");
				if (infoList.size() >= allcount) {
					listview.removeFooterView(moreView);
				} else {
					progressBar_ll.setVisibility(View.GONE);
					moreButton.setVisibility(View.VISIBLE);
				}
				adapter.notifyDataSetChanged();
				// dismissrogressBar();
				break;
			case Constant.MSG_LOAD_ERROR:
				dismissrogressBar();
				MessageTools.showDialogOk(ctx, "请填写至少一项查询条件,建议填写姓名！");
				break;
			}
			isThreadrun = false;
		}
	};

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// dismissPopupWindow();
		if (firstVisibleItem + visibleItemCount == totalItemCount
				&& notfirstTime && (allcount > infoList.size()) && !isThreadrun) {
			// loadWaitPanel();
			// //开线程去下载网络数据
			// new Thread(sendable).start();
		}
	}

	// 请求服务器
	private Runnable sendable = new Runnable() {
		public void run() {
			if (!BphsConstants.isNetAvailable) {
				PatientDao dao = new PatientDao(ctx);
				if (StringTools.isNotBlank(name_str)) {
					infoList = dao.getlittleChildList("sPersonName", name_str);
					myhandler.sendEmptyMessage(Constant.MSG_LOAD_OVER);
				} else if (StringTools.isNotBlank(shengfenzheng_str)) {
					infoList = dao.getlittleChildList("sCardNo",
							shengfenzheng_str);
					myhandler.sendEmptyMessage(Constant.MSG_LOAD_OVER);
				} else if (StringTools.isNotBlank(dangan_num_str)) {
					infoList = dao.getlittleChildList("sNo", dangan_num_str);
					myhandler.sendEmptyMessage(Constant.MSG_LOAD_OVER);
				} else {
					myhandler.sendEmptyMessage(Constant.MSG_LOAD_ERROR);
				}

			} else {
				isThreadrun = true;
				String requestUrl = BphsURL
						.getCommonPath("GetChildrenList_URL");
				Log.i(tag, "查询:content" + requestUrl);
				String methodName = BphsURL
						.getCommonPath("GetChildrenList_METHOD");
				JSONObject data = new JSONObject();
				// {"sAreaCode":"340800","iCurrentPageIndex":"1","iPageSize":"10"}
				try {
					UserLoginInfo info = UserLoginInfo.getInstances();
					data.put("sAreaCode", info.getsManagementDivisionCode());//
					if (jiciNum != 0) {
						data.put("iCurrentPageIndex", jiciNum + "");// ( * 10 +
																	// 1)
					} else {
						data.put("iCurrentPageIndex", "1");
					}
					data.put("iPageSize", "10"); //
					data.put("sNo", dangan_num_et.getText()); //
					data.put("sPersonName", name_et.getText()); //
					data.put("sCardNo", shengfenzheng_et.getText()); //
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				content = WebServiceUtils.requestByParams(methodName,
						data.toString(), requestUrl);
				if (StringUtils.isNotBlank(content)) {
					try {
						Log.i(tag, "返回的查询结果" + content);
						// String result= content.replaceAll("\\\\", "");
						// Log.i(tag, "返回的查询结果"+result);
						JSONObject json = new JSONObject(content);
						// Log.i(tag, "返回的查询结果"+result);"AllCount":0,
						// allcount= 28;
						allcount = json.getLong("AllCount");
						if (allcount == 0) {
							runOnUiThread(new Runnable() {
								public void run() {
									MessageTools.showDialogOk(ctx, "暂无此人信息");
								}
							});
						}
						JSONObject jo = new JSONObject(json.getString("Data"));
						JSONArray jsonArray = (JSONArray) jo.get("Table");
						for (int i = 0; i < jsonArray.length(); ++i) {
							JSONObject o = (JSONObject) jsonArray.get(i);
							LittleChildBean info = new LittleChildBean(
									o.getString("sPersonID"),
									o.getString("sNo"),
									o.getString("sPersonName"),
									o.getString("sSexName"),
									o.getString("sSexCode"),
									o.getString("dBirthday"),
									o.getString("sCardNo"),
									o.getString("sPhone"),
									o.getString("sRegisterNo"),
									o.getString("dRegisterDate"),
									o.getString("gKey"),
									o.getString("VisitingCount"),
									o.getString("CIRsAreaCode"),o.getString("sphoto"));
							if (allcount == 1) {
								// info.setCheck(true);
								xuanzhong_tiao = info;
							}

							infoList.add(info);
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (notfirstTime) {
						myhandler.sendEmptyMessage(Constant.SHOW_UPDATE);
					} else {
						myhandler.sendEmptyMessage(Constant.MSG_LOAD_OVER);
					}
				}
			}
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.chaxuan_btn:// 查询按钮
			// if (!BphsConstants.sAndroidReader) {
			xuanzhong_tiao = null;
			current_xzCheckbox = null;
			jiciNum = 1;
			moreButton.setVisibility(View.VISIBLE);
			name_str = name_et.getText().toString().trim();
			dangan_num_str = dangan_num_et.getText().toString().trim();
			shengfenzheng_str = shengfenzheng_et.getText().toString().trim();
			if (infoList.size() > 0) {
				listview.removeFooterView(moreView);
			}
			infoList.clear();
			allcount = 0;
			notfirstTime = false;
			loadWaitPanel();
			new Thread(sendable).start();
			// } else {
			// loadWaitPanel();
			// Intent intent = new Intent(this, CardActivity.class);
			// startActivityForResult(intent, 1);
			// }
			return;
		case R.id.card_chaxuan_btn:
			loadWaitPanel();
			// Intent intent1 = new Intent(this, CardActivity.class);
			// startActivityForResult(intent1, 1);
			break;
		case R.id.quick_suifang:// 随访按钮
			if (current_xzCheckbox == null && infoList.size() > 1) {
				MessageTools.showDialogOk(ctx, "请选择需要操作的数据,并且只能选择一项！");
				return;
			}
			if (xuanzhong_tiao != null) {
				if (TextUtils.isEmpty(xuanzhong_tiao.getSphoto())) {
					MessageTools.showDialogOk(ctx, "照片为空");
				} else {
                    GotoActivityHelper.gotoFaceDetecetionActivity(act, xuanzhong_tiao.getsPersonName(), xuanzhong_tiao.getsCardNo(), xuanzhong_tiao.getSphoto(),"", xuanzhong_tiao, "2");
                }} else {
				MessageTools.showDialogOk(ctx, "请选择需要操作的数据,并且只能选择一项！");
			}
			return;
		case R.id.ll_popup_xuanzhong:
			if (current_xzCheckbox != null) {
				current_xzCheckbox.setChecked(false);
			}
			xzCheckbox.setChecked(true);
			current_xzCheckbox = xzCheckbox;
			break;
		case R.id.weitj_suifang:
			Intent intent = new Intent(act, SubmitInfoListActivity.class);
			intent.putExtra("mangeType", "儿童保健随访");
			startActivity(intent);
			// toNoFinish(SubmitInfoListActivity.class);
			break;
		case R.id.xindian_jiance_bt:// 心电检测按钮
			if (1 != BphsConstants.deviceBranchType) {
				MessageTools.showDialogOk(ctx, "此功能暂时只支持盖瑞设备！");
				return;
			}

			if (current_xzCheckbox == null && infoList.size() > 1) {
				MessageTools.showDialogOk(ctx, "请选择需要操作的数据,并且只能选择一项！");
				return;
			}
			if (xuanzhong_tiao != null) {
				Intent intent0 = new Intent(act, XDpersonActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString("sPersonID", xuanzhong_tiao.getsPersonID());
				bundle.putString("sNo", xuanzhong_tiao.getsNo());
				bundle.putString("sPersonName", xuanzhong_tiao.getsPersonName());
				bundle.putString("sCardNo", xuanzhong_tiao.getsCardNo());
				intent0.putExtras(bundle);
				startActivity(intent0);
			} else {
				toNoFinish(XDpersonActivity.class);
			}
			return;
		case R.id.ll_popup_chakan:
			break;
		case R.id.ll_popup_quxiao:
			break;
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.d(tag, "屏蔽 home,back,menu键keyCode:" + keyCode);
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Log.d(tag, "BACK键捕获。to BACK");
			act.finish();
			act.overridePendingTransition(android.R.anim.slide_in_left,
					android.R.anim.slide_out_right);
			return true;
		}
		if (KeyEvent.KEYCODE_HOME == keyCode) {
			Log.d(tag, "home键捕获。to home");
			toHome();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private class ListAdapter extends BaseAdapter {

		public int getCount() {
			return infoList.size();
		}

		public Object getItem(int position) {
			return infoList.get(position);
		}

		public long getItemId(int position) {

			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = LayoutInflater.from(act);

//			convertView = inflater.inflate(R.layout.childcare_item, null);
//			TextView dangan_num_tv = (TextView) convertView
//					.findViewById(R.id.dangan_num_tv);
//			TextView name_tv = (TextView) convertView
//					.findViewById(R.id.name_tv);
//			TextView sex_tv = (TextView) convertView.findViewById(R.id.sex_tv);
//			TextView birthday_tv = (TextView) convertView
//					.findViewById(R.id.birthday_tv);
//			TextView shengfenzheng_tv = (TextView) convertView
//					.findViewById(R.id.shengfenzheng_tv);
//			TextView baojian_code_tv = (TextView) convertView
//					.findViewById(R.id.baojian_code_tv);
//			TextView jiance_date_tv = (TextView) convertView
//					.findViewById(R.id.jiance_date_tv);
//
//			CheckBox cb = (CheckBox) convertView
//					.findViewById(R.id.xuanzhong_cb);
//			TextView tv_tijiancishu = (TextView) convertView
//					.findViewById(R.id.tijian_cishu_tv);

			if (convertView==null) {
				convertView = inflater.inflate(R.layout.childcare_item, null);
			}
			TextView dangan_num_tv = (TextView) AbstractViewHolder.get(convertView, R.id.dangan_num_tv);
			TextView name_tv = (TextView) AbstractViewHolder.get(convertView, R.id.name_tv);
			TextView sex_tv = (TextView) AbstractViewHolder.get(convertView, R.id.sex_tv);
			TextView birthday_tv = (TextView) AbstractViewHolder.get(convertView, R.id.birthday_tv);
			TextView shengfenzheng_tv = (TextView) AbstractViewHolder.get(convertView, R.id.shengfenzheng_tv);
			TextView baojian_code_tv = (TextView) AbstractViewHolder.get(convertView, R.id.baojian_code_tv);
			TextView jiance_date_tv = (TextView) AbstractViewHolder.get(convertView, R.id.jiance_date_tv);

			CheckBox cb = (CheckBox) AbstractViewHolder.get(convertView, R.id.xuanzhong_cb);
			TextView tv_tijiancishu = (TextView)AbstractViewHolder.get(convertView, R.id.tijian_cishu_tv);

			tv_tijiancishu.setText(infoList.get(position).getVisitingCount());

			dangan_num_tv.setText(infoList.get(position).getsNo());
			name_tv.setText(infoList.get(position).getsPersonName());
			sex_tv.setText(infoList.get(position).getsSexName());

			birthday_tv.setText(getdatas(CommonUtil.String2date(infoList.get(
					position).getdBirthday())));
			shengfenzheng_tv.setText(infoList.get(position).getsCardNo());
			baojian_code_tv.setText(infoList.get(position).getsRegisterNo());
			jiance_date_tv.setText(getdatas(CommonUtil.String2date(infoList
					.get(position).getdRegisterDate())));

			cb.setChecked(infoList.get(position).isCheck());
			if (cb.isChecked()) {
				convertView.setBackgroundColor(Color.parseColor("#ff00CED1"));
			}
			else {
				convertView.setBackgroundColor(Color.WHITE);
			}
			return convertView;
		}
	}

	public static String getdatas(String Resouce) {
		String reSut = "";
		try {
			SimpleDateFormat f = new SimpleDateFormat("yyyy-mm-dd");
			reSut = f.format(f.parse(Resouce.replace("/", "-")));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return reSut;
	}

	@Override
	public void onDestroy() {

		// dismissPopupWindow();
		if (mUsbReceiver != null) {
			try {
				this.unregisterReceiver(mUsbReceiver);
			} catch (Exception e) {
				e.printStackTrace();

			}
		}

		super.onDestroy();
        if (mDevice != null) {
            mDevice.close();
            mDevice.uninit();
        }

        if (mInspector != null) {
            mInspector.uninit();
        }
	}

	@Override
	public void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		if (mode == 1) {
			new AlertDialog.Builder(ChildCareManageActivity.this)
					.setTitle("提示").setMessage("目前处于OTG模式！")
					.setPositiveButton("确定", null).show();
			return;
		}
		if (mode == 3) {
			new AlertDialog.Builder(ChildCareManageActivity.this)
					.setTitle("提示").setMessage("目前处于蓝牙模式！")
					.setPositiveButton("确定", null).show();
			return;
		}
		// mHandler.sendEmptyMessageDelayed(MESSAGE_CLEAR_ITEMS, 0);
		if (readflag == 1) {
			return;
		}
		inintent = intent;
		readflag = 1;
		shengfenzheng_et.setText("");
		ReadCardAPI.writeFile("come into onNewIntent 2");
		Readingtext.setVisibility(View.VISIBLE);
		mHandler.sendEmptyMessageDelayed(MESSAGE_VALID_NFCBUTTON, 0);

	}

	@Override
	public void onPause() {
		super.onPause();
		// mAdapter.disableForegroundDispatch(this);
		if (mode == 1)
			return;
		if (mode == 3)
			return;
		if (mAdapter != null)
			stopNFC_Listener();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mode == 1)
			return;
		if (mode == 3)
			return;
		ReadCardAPI.writeFile("come into onResume 1");
		if (mAdapter != null)
			startNFC_Listener();
		ReadCardAPI.writeFile("come into onResume 2");
		ReadCardAPI.writeFile("pass onNewIntent 1.111111 action="
				+ getIntent().getAction());
	}

	private void startNFC_Listener() {
		mAdapter.enableForegroundDispatch(this, pi,
				new IntentFilter[] { tagDetected }, mTechLists);
		// mAdapter.enableForegroundDispatch(this, pi,
		// new IntentFilter[] { tagDetected }, null);
	}

	private void stopNFC_Listener() {
		mAdapter.disableForegroundDispatch(this);
	}

	private void init_NFC() {
		// nfcIntent = new Intent(getApplicationContext(),
		// interfaceActivity.class)
		// .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		pi = PendingIntent.getActivity(this, 0, new Intent(this, getClass())
				.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
		// tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
		tagDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);// .ACTION_TAG_DISCOVERED);
		tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
		mTechLists = new String[][] { new String[] { NfcB.class.getName() } };
	}

	private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";

	private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (ACTION_USB_PERMISSION.equals(action)) {
				synchronized (this) {
					UsbDevice device = (UsbDevice) intent
							.getParcelableExtra(UsbManager.EXTRA_DEVICE);

					if (intent.getBooleanExtra(
							UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
						if (device != null) {
							mHandler.sendEmptyMessageDelayed(
									MESSAGE_VALID_OTGBUTTON, 0);
						}
					} else {
					}
				}
			}
		}
	};
	private final Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			int tt;
			switch (msg.what) {
			case MESSAGE_VALID_BTBUTTON:
				ReadCardAPI.setmac(addressmac);
				tt = ReadCardAPI.BtReadCard(btAdapt);
				Log.e("For Test", " ReadCard TT=" + tt);
				if (tt == 2) {
					new AlertDialog.Builder(ChildCareManageActivity.this)
							.setTitle("提示").setMessage("接收数据超时！")
							.setPositiveButton("确定", null).show();
				}

				if (tt == 41) {
					new AlertDialog.Builder(ChildCareManageActivity.this)
							.setTitle("提示").setMessage("读卡失败！")
							.setPositiveButton("确定", null).show();
				}
				if (tt == 42) {
					new AlertDialog.Builder(ChildCareManageActivity.this)
							.setTitle("提示").setMessage("没有找到服务器！")
							.setPositiveButton("确定", null).show();
				}
				if (tt == 43) {
					new AlertDialog.Builder(ChildCareManageActivity.this)
							.setTitle("提示").setMessage("服务器忙！")
							.setPositiveButton("确定", null).show();
				}
				if (tt == 90) {
					shengfenzheng_et.setText(ReadCardAPI.CardNo());

					ReadCardAPI.release();
				}

				readflag = 0;
				Readingtext.setVisibility(View.GONE);
				break;
			case MESSAGE_VALID_NFCBUTTON:
				ReadCardAPI.writeFile("come into MESSAGE_CLEAR_ITEMS 1");
				tt = ReadCardAPI.NfcReadCard(inintent);
				// tt=testReadCardAPI.ReadCard();
				ReadCardAPI.writeFile("come into MESSAGE_CLEAR_ITEMS 2");
				Log.e("For Test", " ReadCard TT=" + tt);
				if (tt == 2) {
					new AlertDialog.Builder(ChildCareManageActivity.this)
							.setTitle("提示").setMessage("接收数据超时！")
							.setPositiveButton("确定", null).show();

				}

				if (tt == 41) {
					new AlertDialog.Builder(ChildCareManageActivity.this)
							.setTitle("提示").setMessage("读卡失败！")
							.setPositiveButton("确定", null).show();
				}
				if (tt == 42) {
					new AlertDialog.Builder(ChildCareManageActivity.this)
							.setTitle("提示").setMessage("没有找到服务器！")
							.setPositiveButton("确定", null).show();
				}
				if (tt == 43) {
					new AlertDialog.Builder(ChildCareManageActivity.this)
							.setTitle("提示").setMessage("服务器忙！")
							.setPositiveButton("确定", null).show();
				}
				if (tt == 90) {
					shengfenzheng_et.setText(ReadCardAPI.CardNo());
					ReadCardAPI.release();
					getIDCARDINFO();
				}
				readflag = 0;
				Readingtext.setVisibility(View.GONE);
				break;
			case MESSAGE_VALID_OTGBUTTON:
				tt = ReadCardAPI.ConnectStatus();
				Log.e("For Test", " ConnectStatus TT=" + tt);
				if (tt == 0) {
					new AlertDialog.Builder(ChildCareManageActivity.this)
							.setTitle("提示").setMessage("设备未连接！")
							.setPositiveButton("确定", null).show();

					Readingtext.setVisibility(View.GONE);
					break;
				}
				if (tt == 2) {

					Readingtext.setVisibility(View.GONE);
					break;
				}
				tt = ReadCardAPI.OTGReadCard();
				// Log.e("For Test"," ReadCard TT="+tt);
				if (tt == 2) {
					new AlertDialog.Builder(ChildCareManageActivity.this)
							.setTitle("提示").setMessage("接收数据超时！")
							.setPositiveButton("确定", null).show();
					/*
					 * onredo.setEnabled(true); onredo.setFocusable(true);
					 * onredo.setBackgroundResource(R.drawable.sfz_dq);
					 */
					Readingtext.setVisibility(View.GONE);
					break;
				}
				if (tt == 41) {
					new AlertDialog.Builder(ChildCareManageActivity.this)
							.setTitle("提示").setMessage("读卡失败！")
							.setPositiveButton("确定", null).show();
					/*
					 * onredo.setEnabled(true); onredo.setFocusable(true);
					 * onredo.setBackgroundResource(R.drawable.sfz_dq);
					 */
					Readingtext.setVisibility(View.GONE);
					break;
				}
				if (tt == 42) {
					new AlertDialog.Builder(ChildCareManageActivity.this)
							.setTitle("提示").setMessage("没有找到服务器！")
							.setPositiveButton("确定", null).show();
					/*
					 * onredo.setEnabled(true); onredo.setFocusable(true);
					 * onredo.setBackgroundResource(R.drawable.sfz_dq);
					 */
					Readingtext.setVisibility(View.GONE);
					break;
				}
				if (tt == 43) {
					new AlertDialog.Builder(ChildCareManageActivity.this)
							.setTitle("提示").setMessage("服务器忙！")
							.setPositiveButton("确定", null).show();
					/*
					 * onredo.setEnabled(true); onredo.setFocusable(true);
					 * onredo.setBackgroundResource(R.drawable.sfz_dq);
					 */
					Readingtext.setVisibility(View.GONE);
					break;
				}
				if (tt == 90) {
					shengfenzheng_et.setText(ReadCardAPI.CardNo());

					String s = ReadCardAPI.CardNo().substring(6, 14);

					ReadCardAPI.release();
					Readingtext.setVisibility(View.GONE);
					break;
				}
				break;
			}
		}
	};

	public void getIDCARDINFO() {
		jiciNum = 1;
		moreButton.setVisibility(View.VISIBLE);
		name_str = name_et.getText().toString().trim();
		dangan_num_str = dangan_num_et.getText().toString().trim();
		shengfenzheng_str = shengfenzheng_et.getText().toString().trim();
		if (infoList.size() > 0) {
			listview.removeFooterView(moreView);
		}
		infoList.clear();
		allcount = 0;
		notfirstTime = false;
		loadWaitPanel();
		new Thread(sendable).start();
	}
}